package com.lcx.hw.controller;

import com.lcx.hw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    //user/register/{email}/{password}/{code}
    @GetMapping("/register/{email}/{password}/{code}")
    public Integer register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code,
                            HttpServletResponse response){
        try {
            Integer integer = userService.register(email,password,code);
            if(!"0".equals(password) && integer == 0){
                //签发token
                String token = userService.saveToken(email);
            }
            return integer;
        } catch (Exception e) {
            e.printStackTrace();
            return 3;
        }
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email){
        try {
            return userService.isRegistered(email);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email,
                        @PathVariable("password") String password,
                        HttpServletResponse response){
        try {
            String token = userService.login(email, password);
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token){
        try {
            return userService.info(token);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
